using System.Windows;
using System.Windows.Controls;
using DotNet.Utilities;

namespace WPFTemplateLib.Controls.Panels
{
	/// <summary>
	/// [自定义控件] 自动在元素之间添加分隔线的 StackPanel
	/// </summary>
	public class SeparatorStackPanel : StackPanel
	{
		//private readonly Separator _separator = new Separator();

		#region 依赖属性

		#region [依赖属性] 分隔线样式
		/// <summary>
		/// 分隔线样式
		/// </summary>
		public Style SeparatorStyle
		{
			get => (Style)GetValue(SeparatorStyleProperty);
			set => SetValue(SeparatorStyleProperty, value);
		}
		/// <summary>
		/// [依赖属性] 分隔线样式
		/// </summary>
		public static readonly DependencyProperty SeparatorStyleProperty =
			 DependencyProperty.Register(nameof(SeparatorStyle), typeof(Style), typeof(SeparatorStackPanel), new PropertyMetadata(null, SeparatorStyleChangedCallback));
		/// <summary>
		/// 分隔线样式 变动处理方法
		/// </summary>
		private static void SeparatorStyleChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
		{
			if(e.NewValue is Style style && style.TargetType == typeof(Separator))
			{
				((SeparatorStackPanel)d).SetSeparatorStyle(style);
			}
		}
		#endregion

		#endregion

		#region 方法

		/// <summary>
		/// 设置分隔线的样式
		/// </summary>
		/// <param name="style"></param>
		private void SetSeparatorStyle(Style style)
		{
			//_separator.Style = style;
			foreach(UIElement child in Children)
			{
				if(child.GetType() != typeof(Separator))
					continue;

				((Separator)child).Style = style;
			}
		}

		/// <inheritdoc />
		protected override void OnVisualChildrenChanged(DependencyObject visualAdded, DependencyObject visualRemoved)
		{
			base.OnVisualChildrenChanged(visualAdded, visualRemoved);

			var index = Children.Count - 1;

			if(visualAdded != null)
			{
				//Console.WriteLine("子元素被添加: " + visualAdded);
				if(index > 0 && Children[index - 1] is not Separator)
				{
					//Children.Insert(index, ClassHelper.CloneObject(_separator));

					var separator = new Separator();
					if(SeparatorStyle != null)
						separator.Style = SeparatorStyle;

					Children.Insert(index, separator);
				}
			}

			if(visualRemoved != null)
			{
				//Console.WriteLine("子元素被移除: " + visualRemoved);
				if(index > 0 && Children[index] is Separator separator)
				{
					Children.Remove(separator);
				}
			}

			//InvalidateMeasure();
			//InvalidateArrange();
		}

		///// <inheritdoc />
		//protected override Size MeasureOverride(Size availableSize)
		//{
		//	// 测量逻辑
		//	return base.MeasureOverride(availableSize);
		//}

		///// <inheritdoc />
		//protected override Size ArrangeOverride(Size finalSize)
		//{
		//	// 布局逻辑
		//	return base.ArrangeOverride(finalSize);
		//}

		#endregion
	}
}
